﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.XPath;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerUI;

namespace KwaiXiaoDian.OpenApi.Swagger
{
    /// <summary>
    /// Swagger 扩展类
    /// </summary>
    public static class SwaggerExtensions
    {
        /// <summary>
        /// 注册 swagger 
        /// </summary>
        /// <param name="services">The services.</param>
        public static void AddSwagger(this IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                var enterAssemblyName = typeof(SwaggerExtensions).Assembly.GetName().Name;

                c.DocumentFilter<SwaggerDocumentFilter>();
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "KwaiXiaoDian接口文档", Version = "v1.0" });

                var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "KwaiXiaoDian.*.xml");
                foreach (var file in files)
                {
                    c.IncludeXmlComments(file);
                }
 
                var webFiles = files.FirstOrDefault(u => Path.GetFileNameWithoutExtension(u) == enterAssemblyName);
                if (webFiles != null)
                {
                    c.OperationFilter<SwaggerOperationFilter>(new XPathDocument(webFiles));
                }

                //让swagger支持带Jwt报文头
                var scheme = new OpenApiSecurityScheme()
                {
                    Description = "Authorization header. \r\nExample: 'Bearer 12345abcdef'",
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Authorization"
                    },
                    Scheme = "oauth2",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                };
                c.AddSecurityDefinition("Authorization", scheme);
                var requirement = new OpenApiSecurityRequirement();
                requirement[scheme] = new List<string>();
                c.AddSecurityRequirement(requirement);
            });
        }

        /// <summary>
        /// 使用 swagger
        /// </summary>
        /// <param name="app">The application.</param>
        public static void UseSwaggerConfig(this IApplicationBuilder app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.DocExpansion(DocExpansion.None);
                c.DefaultModelExpandDepth(10);
                c.DocumentTitle = "KwaiXiaoDian接口文档v1.0";
                c.RoutePrefix = "";
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "KwaiXiaoDian接口文档v1.0");
            });
        }
    }
}
